﻿<script type="text/javascript">
    ///<reference path="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js" />
    ///<reference path="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js" />
    ///<reference path="js/lib.js" />

    $(document).ready(function () {
        // LocalInit();



        $("#GalaxySearch").autocomplete(
          {
              minLength: 3,
              source: function (request, response) {
                  var dataSetId = $("#DataSetSelect > option:selected").val();
                  GetJsonSproc("usp_searchgalaxybyname",
                      {
                          wildcard: request.term,
                          DataSetId: dataSetId
                      },
                      function (json) {
                          response(json);
                      });
              },
              select: function (event, ui) {
                  event.preventDefault();
                  $("#DrawButton").show();
                  //console.dir(ui);
                  //alert(ui.item.label);
                  $("#GalaxySearch").val(ui.item.label);
                  GalaxyId = ui.item.value;

              }
          });

        GetJsonSproc("usp_GetDataSets",

          function (json) {

              var sel = $("#DataSetSelect");
              sel.change(UpdateFilters);
              sel.empty();

              $.each(json, function (key, value) {
                  console.dir(value);
                  var o = $("<option>").text(value.Name).val(value.ID);
                  sel.append(o);
              });


              UpdateFilters();
          });

    }
    );

    function renderMorphFilterPicker()
    {
        var container = $("#filterPicker");
        container.empty();

        $.each(morphFilters, function (key, item)
        {
            var cb = $("<input type='checkbox' id='filter" + item.id + "'/>")
            var lable = $("<label for='filter" + item.id + "'/>").text(item.Name);
            cb.data("index", key);
            cb.data("name", item.Name);
            
            cb.appendTo(container);
            lable.appendTo(container);
        });

    }


    function UpdateFilters()
    {
        var dataSetId = $("#DataSetSelect > option:selected").val();

     /*   if($("#DataSetSelect > option:selected").text() == "2MRS North")
        {
            options.yaxis.max = 90;
            options.yaxis.min = 0;
        }
        else{
            options.yaxis.max = 0;0
            options.yaxis.min = -90;
        }*/


        GetJsonSproc("usp_GetMorphologyFilters",
           {
               DataSetId: dataSetId
           },
       function (json) {
           morphFilters = json;
           renderMorphFilterPicker();
       });

        cahceDataForPlot();
    }

    var placeholder;

    var symbols = ["circle", "triangle", "diamond", "square", "cross"];
    var colors = ["black", "orange", "green", "blue", "purple"];

   /* var morphFilters =
        [
            {
                name: "Spiral",
                regex: new RegExp("^[0-9]{1}.*$", "i")
            },
            {
                name: "Elliptical",
                regex: new RegExp("^-[4-7]{1}.*$", "i")
            }
        ];*/

    var morphFilters;

    /*
    function processDatapointsForAll (plot, series, datapoints)
    {
        var points = datapoints.points, ps = datapoints.pointsize;
        for (var i = 0; i < points.length; i += ps) {
            var glon = points[i];
            var glat = points[i + 1];

            // var auxAngle = (Math.PI * Math.Sin(glat)) / ()

            var x, y;

            x = glon;
            y = glat;

            var glatRad = glat * (Math.PI / 180);
            var glonRad = glon * (Math.PI / 180);

            x = ((glon - _galaxyLon) * Math.cos(glatRad)) + 180
            y = glat;

           // console.log("glon=" + glon + " glat=" + glat + " x=" + x + " y=" + y);

            points[i] = x;
            points[i + 1] = y;

        }
    }
    var _galaxyLon = 180.0;
   function processDatapointsForGalaxy(plot, series, datapoints)
    {
        var points = datapoints.points, ps = datapoints.pointsize;
        for (var i = 0; i < points.length; i += ps) {
            var glon = points[i];
            var glat = points[i + 1];

            // var auxAngle = (Math.PI * Math.Sin(glat)) / ()

            var x, y;

            x = glon;
            y = glat;

            var glatRad = glat * (Math.PI / 180);
            var glonRad = glon * (Math.PI / 180);

            x = ((glon - _galaxyLon) * Math.cos(glatRad)) + 180
            y = glat;

            console.log("glon=" + glon + " glat=" + glat + " x=" + x + " y=" + y);

            points[i] = x;
            points[i + 1] = y;

        }
    }*/



  /*  var hooks = 
       
    {
        processDatapoints: processDatapointsForAll
        
    }
    */

    var options =
       {
           axisLabels: {
               show: true
           },
           legend:
               {
                   show: true,
                   position: "ne",
                   container: $("#legend")
               },
           zoom: {
               interactive: true
           },
           pan: {
               interactive: true
           },
           series:
              {
                  // lines: { show: true },
                  points: { show: true, radius: 1 },
                  // data: chartData,
                  // color: "black"
              },
           xaxis:
               {
                //   min: 0,
                //   max: 360,
                //   reserveSpace: true,
                   axisLabel: "GLon",
                   position: 'bottom'
                  
               },
               
            yaxis:
                {
              //      min: -90,
               //    max: 90,
               //    reserveSpace: true,
                    axisLabel: "GLat",
                    position: 'left',
                }///,
          //  hooks: hooks
            
       };
     
    function BuildSeries(label, subset, symbol, color)
    {
        var arr = BuildSeriesArray(subset);
        var series = {
            label: label,
            data: arr,
            color: color,
            points: { symbol: symbol  }
        }

        return series;
    }

    function BuildSeriesArray(subset)
    {

        var chartData = [];
        console.dir(subset);
        $.each(subset, function (key, value) {
            // console.log(value)
           // if (item == null)
              //  return;
            var item = [value.glon, value.glat];
            chartData.push(item)
        });
        return chartData;
    }

    function getMatcingGalaxies(data, filter)
    {
        var arr = [];
      //  console.dir(data);
        for (var i = 0; i < data.length; i++)
        {
            var galaxy = data[i];
            if (galaxy == null)
                continue;
            
            if (galaxy.Morphology.match(filter.RegexFilter))
            {
              //  console.log(galaxy.Morphology + " matches filter " + filter.name + "; " + filter.regex);
                arr.push(galaxy);
            }
        }
       return arr;
    }

    function plotData(json, mode)
    {
      //  console.dir(GalaxyId);
       
         placeholder = $("#plotchart");
         var dataSetName = $("#DataSetSelect > option:selected").text();
         var dataSeries = [];
         var filters = [];
        
       //  console.dir(sourceArr);

        
      /*   for (var i = 0; i < morphFilters.length; i++)
         {
             var filter = morphFilters[i];
             dataSeries.push(BuildSeries(filter.Name, getMatcingGalaxies(json, filter), symbols[dataSeries.length], colors[dataSeries.length]));
             // dataSeries.push(BuildSeries("50-100",json.slice(50, 100), symbols[dataSeries.length], colors[dataSeries.length]));
         }*/
       

         if (mode == "all")
         {

             var filter = {
                 Name: "All",
                 RegexFilter: new RegExp(".*", "i")
             };
             dataSeries.push(BuildSeries(filter.Name, getMatcingGalaxies(json, filter), symbols[dataSeries.length], colors[dataSeries.length]));
              filters.push("All");
         }
        else

         $("#filterPicker input").each(function (key, item) {
             var cb = $(item);
             if(cb.is(":checked"))
             {
                 var filter = morphFilters[cb.data("index")];
                 dataSeries.push(BuildSeries(filter.Name, getMatcingGalaxies(json, filter), symbols[dataSeries.length], colors[dataSeries.length]));
                 filters.push(cb.data("name"));
             }
         });



        // console.dir(dataSeries);

        //  console.log(chartData);
         if (mode == "galaxy") {

             var sourceGalaxy;
             for (var a = 0; a < json.length; a++) {
                 var item = json[a];
                 console.dir(item);
                 if (item.id == GalaxyId) {
                     sourceGalaxy = item;
                     //_galaxyLon = sourceGalaxy.glon;
                     json[a] = null; // remove source galaxy from the data set to avoide overlapping.
                     break;
                 }
             }

             //   console.dir(json);
          
             var sourceArr = [];
            

             sourceArr.push(sourceGalaxy);
             dataSeries.push(BuildSeries("Self", sourceArr, "diamond", "red"));
         }

         if (dataSeries.length > 0)
         {
             var plot = $.plot(placeholder, dataSeries, options);
             $("#legendContainer #label").text(dataSetName);
             $("#legendContainer").show();
         }
         placeholder.resizable().parents(".ui-widget").css("visibility", "visible");
         placeholder.parent().siblings(".ui-widget-header").text(GetWatermarkString(filters.join(", ")));

    }

    var _data;

    function ClearPlot()
    {
        _data = [];
        plot(_data, "dataset");
    }
   /*

    function plotall()
    {
        plotData(_data, "all");
    }
    */

    function plot()
    {
  
      //  _galaxyLon = 180.0;
        console.log("in plot");
        console.dir(options);
     //   options.yaxis.reserveSpace = true;
      //  options.xaxis.reserveSpace = true;
       plotData(_data, "dataset");
            
      
        // options.hooks=hooks;
      
    }

    function plotGalaxy()
    {

        //  delete options.hooks;
        console.log("in plot galaxy");
        //console.dir(options);
       // options.yaxis.reserveSpace = false;
      //  options.xaxis.reserveSpace = false;
        var sproc = "getnearbyobjectsandprimary";

        var Distance = $("#Distance").val();

        var parms = {
            startobject: GalaxyId,
            FittingRange: Distance,
            DataSetId: $("#DataSetSelect > option:selected").val(),

            Is3D: false

        };

        if ($("#Is3D").is(":checked"))
        {
            parms.Is3D = true;

        }
        
        GetJsonSproc(sproc,
            parms, function (json) {
                plotData(json, "galaxy")
            });
    }
    /*
    function plotGalaxyAll()
    {

        var sproc = "usp_GetNearbyObjects";

        if($("#Is3D").is(":checked"))
        sproc += "3D";


        var Distance = $("#Distance").val();
        GetJsonSproc("sproc",
            {
                startobject: GalaxyId,
                distance: Distance
            }, function (json) {
                plotData(json, "all")
            });
    }*/

    function GetWatermarkString(filters)
    {

        var dataCatalog = $("#DataSetSelect > option:selected").text();

        return dataCatalog + " | Viewing: " + filters + " | Galactic (http://galactic.codeplex.com)";
    }



</script>


    
<div class="mt mb">
    <div>
       Data Set: <select id="DataSetSelect"></select>
    
        <input id="GalaxySearch" type="text" placeholder="Galaxy" />
        <input id="Distance" type="number"  style="width:3em;" placeholder="FR" />
        <input type="checkbox" id="Is3D" /> <label for="Is3D">3D Projection?</label>
        <span class="button" data-icon="fa-bar-chart-o" onclick="plotGalaxy()">Plot Galaxy</span>
      <!--- <span class="button" data-icon="fa-bar-chart-o" onclick="plotGalaxyAll()">Plot All</span> -->
    </div>
    Include Morph: <div id="filterPicker" style="display:inline-block;"></div>
    <span class="button" data-icon="fa-bar-chart-o" onclick="plot();">Plot Dataset</span>

  <!----  <span class="button" data-icon="fa-bar-chart-o" onclick="plotall()">Plot All in Dataset</span> -->
   

   

</div>

<div class="ui-widget" style="float: left; position: relative; visibility:hidden;">
    <div class="ui-widget-header">lkjj;lkj</div>
    <div class="ui-widget-content pad">
        <div id="plotchart" style="width:1080px; height:540px;">
        </div>
    </div>

</div>


<div id="legendContainer" class="ml ui-widget ilb" style='display:none;'>
    <div class="ui-widget-header">Legend</div>
    <div class="ui-widget-content">
        <div id="legend" class=""></div>
        <div id="label"></div>
    </div>
</div>

